package com.zznzzn.androidshixun0826;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    private static final int RESULT_CODE_CAMERA = 101;
    public ListView mlistView = null;
    public View.OnClickListener mbtnListener = null;
    public AdapterView.OnItemClickListener mitemListener = null;
    public ContactLib mcb = null;
    public MyListAdapter madapter ,newListAdapter= null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("emmm");

        mlistView = findViewById(R.id.list_view);

        mcb = ContactLib.get_lib(this);

        madapter = new MyListAdapter(this,mcb);
        mlistView.setAdapter(madapter);

        mitemListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                madapter.setSelected(position);
                Intent intent = new Intent(MainActivity.this,ContactInfoActivity.class);
                intent.putExtra("index",position);
                intent.putExtra("contact",mcb.getContact(position));
                startActivityForResult(intent,103);//103 for info/edit contact
            }
        };

        mlistView.setOnItemClickListener(mitemListener);

        if (!(PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA))){
            String[] perms = {
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CALL_PHONE
            };
            ActivityCompat.requestPermissions(this,perms,RESULT_CODE_CAMERA);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case RESULT_CODE_CAMERA:
                boolean flag = false;
                for (int i:grantResults
                     ) {
                    if (i != PackageManager.PERMISSION_GRANTED){
                        flag = true;
                    }
                }
                if (flag){
                    Toast.makeText(this,"申请权限失败",Toast.LENGTH_SHORT).show();
                }
        }
    }

    public void Contact_add(){
        Intent intent = new Intent(MainActivity.this,NewContactActivity.class);
        startActivityForResult(intent,101);//101 for new contact

    }

    public void Caculater_start(){
        Intent intent = new Intent(MainActivity.this,MyToolActivity.class);
        startActivityForResult(intent,102);//102 for calculater

    }

    public void show_search(){
        //弹出dialog
        final EditText result = new EditText(MainActivity.this);
        result.setHint("请输入姓名");
        result.setSingleLine();

        AlertDialog dia = new AlertDialog.Builder(this).create();
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == AlertDialog.BUTTON_POSITIVE){
                    String input = result.getText().toString();
                    do_search(input);
                }else{
                    dialog.dismiss();
                }
            }
        };
        dia.setTitle("搜索");
        dia.setIcon(R.drawable.filesearch);

        dia.setView(result);
        dia.setButton(AlertDialog.BUTTON_POSITIVE, "搜索", listener);
        dia.setButton(AlertDialog.BUTTON_NEGATIVE,"取消", listener);
        dia.show();
    }

    public void do_search(String name){ //新建mylistadapter和contactLib，重新绑定listView
        List<Contact> result = mcb.searchContact(name);
        Toast.makeText(MainActivity.this,"搜索到 "+result.size()+"人",Toast.LENGTH_SHORT).show();

        final ContactLib newcb = new ContactLib(result);
        Log.d("----cl",newcb.toString());
        newListAdapter = new MyListAdapter(MainActivity.this,newcb);
        mlistView.setAdapter(newListAdapter);

        mitemListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this,ContactInfoActivity.class);
                Log.d("=========id",position+"");
                //position in old list
                position = mcb.getIndex(newcb.getContact(position));
                //position in new list
                intent.putExtra("index",position);
                Log.d("=========idn",position+"");
                intent.putExtra("contact",mcb.getContact(position));
                startActivityForResult(intent,103);//103 for info/edit contact
            }
        };

        mlistView.setOnItemClickListener(mitemListener);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mcb.flush();
//        restoreData();
        if (requestCode == 101){
            if (resultCode == 502){
                Toast.makeText(this,"取消创建新纪录",Toast.LENGTH_SHORT).show();
            }else if (resultCode == 200){
                Toast.makeText(this,"创建新纪录成功",Toast.LENGTH_SHORT).show();
                Contact xiaoming = (Contact) data.getSerializableExtra("contact");
                mcb.addContact(xiaoming);
                madapter.notifyDataSetChanged();
            }
        }else if (requestCode == 103){
            if (resultCode == 200){
                Toast.makeText(this,"修改记录成功",Toast.LENGTH_SHORT).show();
                madapter.notifyDataSetChanged();
                if (newListAdapter != null){
                    newListAdapter.notifyDataSetChanged();
                }
            }else if (resultCode == 302){
                Toast.makeText(this,"取消修改纪录",Toast.LENGTH_SHORT).show();
            }else if (resultCode == 201){
                Toast.makeText(this,"删除纪录成功",Toast.LENGTH_SHORT).show();
                restoreData();

            }
            madapter.notifyDataSetChanged();
        }
    }


    //actionbar buttons

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater mif = getMenuInflater();
        mif.inflate(R.menu.activity_main_action,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.main_add_user:
                Contact_add();
                return true;
            case R.id.main_calculator:
                Caculater_start();
                return true;
            case R.id.main_search:
                show_search();
                return true;
            case R.id.main_reload:
                restoreData();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }


    }
    public void restoreData(){
        Log.d("----cl",mcb.toString());
        madapter = new MyListAdapter(MainActivity.this,mcb);
        mlistView.setAdapter(madapter);

        mitemListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,ContactInfoActivity.class);
                intent.putExtra("index",position);
                intent.putExtra("contact",mcb.getContact(position));
                startActivityForResult(intent,103);//103 for info/edit contact
            }
        };

        mlistView.setOnItemClickListener(mitemListener);
        Toast.makeText(this,"数据已刷新",Toast.LENGTH_SHORT).show();
        madapter.notifyDataSetChanged();
    }

}
